package JAVA300.第十一章多线程;

/**
 * 实例练习同步问题2
 * 火车票抢票
 */
public class thread_16_synchronized_exp2 {
    public static void main(String[] args) {
        Web12306 c = new Web12306(4,"CGV");
        new Passenger(c,"hqq",2).start();
        new Passenger(c,"qyh",1).start();



    }
}

class Web12306  implements Runnable{
    int available;//可选座位数目
    String name ;//影院

    public Web12306(int available, String name) {
        this.available = available;
        this.name = name;
    }

    public synchronized boolean  bookTickets(int wantSeats){
        if (wantSeats>available){
            return false;
        }else {
            System.out.println("可选座位数目："+available);
            available -= wantSeats;
            //System.out.println("您成功预订座位数目："+wantSeats);
            return true;


        }
    }

    public void run() {
        Passenger p = (Passenger)Thread.currentThread();//线程强转

        boolean flag = this.bookTickets(p.seats);
            if (flag){
                System.out.println("购票成功"+Thread.currentThread().getName()+"-->"+p.seats);
            }else {
                System.out.println("出票失败"+Thread.currentThread().getName()+"票数不够");
            }




    }
}

//购票人

class Passenger extends Thread{//相当于重写Thread

    int seats;

    public Passenger(Runnable targets,String name,int seats) {
        super(targets,name);//一个线程类，一个线程名
        this.seats =seats;
    }



}
